/* eslint-disable default-case */
/* eslint-disable no-unused-expressions */
import { message } from 'antd';
import {
  getListBillData,
  getUnpaidBillsData,
  markData,
  deleteBill,
  checkCreateSuppBillTask,
  getSuppBillProgress,
  checkCreate,
  createBill,
  mergeBill,
  getSuppNameList,
  featchEnterList,
  getBillInformation,
  getBillDetailsData,
  downloadTemplate,
  getWageGenerationListData,
  getOnceListData,
  getOtherData,
  getGenerateBills,
  getCreateGenerateBills,
  singleExportFile,
  mergeExportFile,
  getUploadFile,
  getRespUserList,
} from '@/services/supplybilling';
import * as service from '@/services/socket';

export default {
  state: {
    expandForm: false,
    isFlag: true,
    activeKey: '1',
    formFieldsValue: {},
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proBaseList: {},
    proFbList: [],
    proListData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    billDetailsDataList: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    dataSource: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    wageGenerationData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    onceData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    otherData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    billTaskId: null, // 拿id获取进度
    modalVisible: false,
    showProgress: false,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '生成账单', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/nsBill/downBillException', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    respUserList: [],
  },
  effects: {
    // 获取列表
    *getListBill({ payload }, { call, put }) {
      const response = yield call(getListBillData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: response.data || [],
          currentPage,
          pageSize,
        },
      });
    },

    // 获取未进账单列表
    *getUnpaidBillsList({ payload }, { call, put }) {
      const response = yield call(getUnpaidBillsData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
    },

    // 未进账单数据
    *getEnterList({ payload }, { call, put }) {
      const response = yield call(featchEnterList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'noBillEnteredList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'noBillEnteredList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
    },

    // 删除账单
    *deleteBill({ payload }, { call }) {
      const response = yield call(deleteBill, payload);
      return response;
    },

    // 标记已收费
    *markModelData({ payload, callback }, { call }) {
      const response = yield call(markData, payload);
      callback && callback(response);
    },

    // 判断有无账单任务
    *checkCreateBillTask(_, { call, put }) {
      const response = yield call(checkCreateSuppBillTask);
      if (response.success && response.data) {
        if (response.data.taskCode === 3) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              billTaskId: response.data.billTaskId,
              taskCode: response.data.taskCode,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      }
      return response;
    },

    // 获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getSuppBillProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.rate },
        });
      }
      return response;
    },

    // 生成账单
    updateCheckCreate:[
      function* ({ payload, callback }, { call }) {
        const response = yield call(checkCreate, payload);
        callback && callback(response);
      },
      { type:'throttle',ms:10000 }
  ],
    // 获取生成完账单
    *updateCreateBill({ payload, callback }, { call }) {
      const response = yield call(createBill, payload);
      callback && callback(response);
    },

    // 合并账单
    *mergebilling({ payload, callback }, { call }) {
      const response = yield call(mergeBill, payload);
      callback && callback(response);
    },

    // 签约方列表
    *getSuppList({ payload, callback }, { call }) {
      const response = yield call(getSuppNameList, payload);
      callback && callback(response);
    },

    // 供应商账单详情 - 账单信息
    *billInformation({ payload }, { call }) {
      const response = yield call(getBillInformation, payload);
      return response;
    },

    // 供应商账单详情 - 账单明细
    *getBillDetails({ payload }, { call, put }) {
      const response = yield call(getBillDetailsData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getBillDetailsList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getBillDetailsList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
      return response;
    },

    // 下载模板
    *updownfiles({ payload }, { call }) {
      const response = yield call(downloadTemplate, payload);
      return response;
    },

    // 未进账单的生成账单 - 代发工资代报税列表
    *getWageGenerationList({ payload }, { call, put }) {
      const response = yield call(getWageGenerationListData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'wageGenerationListData',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'wageGenerationListData',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
      return response;
    },

    // 未进账单的生成账单 - 一次性列表
    *getOnceList({ payload }, { call, put }) {
      const response = yield call(getOnceListData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'onceListData',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'onceListData',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
      return response;
    },

    // 未进账单的生成账单 - 其它列表
    *getOtherList({ payload }, { call, put }) {
      const response = yield call(getOtherData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'otherListData',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        response.data &&
          response.data.pageRecords &&
          // eslint-disable-next-line array-callback-return
          response.data.pageRecords.map(ritem => {
            // eslint-disable-next-line no-param-reassign
            ritem.key = `${
              ritem.cardNo // 身份证
            }^${
              ritem.custId // 客户id
            }^${
              ritem.empId // 员工id
            }^${
              ritem.feeYm // 收费年月
            }^${ritem.sendSuppId}^${ritem.defaultFlag}^${ritem.unnaturalCause}`; // 签约方
          });

        yield put({
          type: 'otherListData',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表数据错误：服务端未知错误');
      }
      return response;
    },

    //  未进账单 - 生成账单
    *generateBills({ payload }, { call }) {
      const response = yield call(getGenerateBills, payload);
      return response;
    },

    // 未进账单 - 生成账单
    *createGenerateBills({ payload }, { call }) {
      const response = yield call(getCreateGenerateBills, payload);
      return response;
    },

    // 账单单个下载
    *singleExport({ payload }, { call }) {
      const response = yield call(singleExportFile, payload);
      return response;
    },

    // 账单合并下载
    *mergeExport({ payload }, { call }) {
      const response = yield call(mergeExportFile, payload);
      return response;
    },

    // 供应商账单 - 账单下载
    *uploadFile({ payload }, { call }) {
      const response = yield call(getUploadFile, payload);
      return response;
    },
    // 上传文件:批量进度:获取batchId后获取进度 :batchType：1为生成账单，2为合并账单,3/4:未进账单生成(enterActiveKey)
    uploadFileWithProgress :[
      function* (
      {
        payload: { batchType, params },
      },
      { call, put }
    ) {
      let batchUrl = createBill;
      switch (batchType) {
        case 1:
          batchUrl = createBill;
          break;
        case 2:
          batchUrl = mergeBill;
          break;
        case 3:
          batchUrl = getGenerateBills;
          break;
        case 4:
          batchUrl = getCreateGenerateBills;
          break;
        default:
          break;
      }
      const response = yield call(batchUrl, params);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data && response.data.batchId,
            progressPercent: 0,
          },
        });
        if (batchType === 1 || batchType === 3 || batchType === 4) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: response.data && response.data.taskCode === 3,
            },
          });
          if (response.data.taskCode === 1) {
            if (response.data && response.data.successProp !== 100) {
              yield put({
                type: 'updateModelData',
                payload: {
                  modalVisible: false,
                  showProgress: true,
                },
              });
              yield call(service.socketChannel, {
                type: 'sub',
                data: {
                  to: response.data && (response.data.batchId || response.data),
                  type: 'nsBill',
                },
              });
            } else {
              yield put({
                type: 'updateBatchTask',
                payload: response.data,
              });
            }
          } else if (response.data.taskCode === 3) {
            message.warning('当前有账单任务正在生成，请稍后操作！');
          }
        } else if (batchType === 2) {
          if (response.data && response.data.successProp !== 100) {
            yield put({
              type: 'updateModelData',
              payload: {
                modalVisible: false,
                showProgress: true,
              },
            });
            yield call(service.socketChannel, {
              type: 'sub',
              data: {
                to: response.data && (response.data.batchId || response.data),
                type: 'nsBill',
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        }
      } else {
        // 操作失败
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.supplybilling);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 列表
    noBillEnteredList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        dataSource: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 未进账单的 - 代发工资待报税列表
    wageGenerationListData(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        wageGenerationData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 未进账单的 - 一次性列表
    onceListData(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        onceData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 未进账单的 - 一次性列表
    otherListData(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        otherData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 账单明细列表
    getBillDetailsList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const newData = data.pageRecords;
      if (newData && newData.length) {
        newData.map((item, index) => {
          if (!item.empId) {
            newData[index].onceFee.feeAmo = item.oneOffAmo;
            newData[index].onceFee.detail = item.detail;
          }
          return true;
        });
      }
      const list = Array.isArray(data.pageRecords) ? newData : [];
      return {
        ...state,
        billDetailsDataList: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 更新数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { resultInfo, modalVisible } = state;
      modalVisible = false;
      if (payload.successProp === 100) {
        if (payload.errorCount) {
          resultInfo.errorParams = {
            billTaskId: payload.batchId,
          };
          resultInfo.errorCount = payload.errorCount || 0;
        }
        resultInfo.taskCount = payload.taskNumber;
        resultInfo.billCount = payload.successCount;
        resultInfo.feeYm =
          payload.feeYm &&
          `${payload.feeYm.toString().substr(0, 4)}-${payload.feeYm.toString().substr(4, 5)}`;
        resultInfo.successCount = payload.successCount;
        resultInfo.taskFlag = payload.taskFlag || 1;
        resultInfo = { ...resultInfo, ...payload };
      }
      return {
        ...state,
        modalVisible,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'nsBill':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
